<template>
  <div>
    <div class="p-3">
      <div>
        <a-card :bordered="false" style="height: 820px">
          <a-form
            :model="searchForm"
            layout="inline"
            class="mt-3"
            ref="searchFormRef"
          >
            <a-form-item label="收费时间">
              <a-range-picker v-model:value="value2" show-time />
            </a-form-item>
            <a-form-item label="收费期" name="feeDate">
              <a-date-picker v-model:value="searchForm.feeDate" />
            </a-form-item>
            <a-form-item label="业务类型" name="refundStatus">
              <a-select
                v-model:value="searchForm.refundStatus"
                placeholder="请选择"
                style="width: 200px"
              >
                <a-select-option value="1">增值税普通发票</a-select-option>
                <a-select-option value="2">增值税专用发票</a-select-option>
                <a-select-option value="3">增值税电子发票</a-select-option>
                <a-select-option value="4">普通发票</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="面积使用类型">
              <a-select />
            </a-form-item>
            <a-form-item label="生成应收方式">
              <a-select />
            </a-form-item>
            <a-form-item label="归属机构">
              <a-select />
            </a-form-item>
            <a-form-item>
              <a-button
                type="primary"
                class="mr-3"
                :icon="h(SearchOutlined)"
                @click="onSearch"
                >查询</a-button
              >
              <a-button
                type="primary"
                :icon="h(RedoOutlined)"
                class="mr-3"
                @click="onReset"
                >重置</a-button
              >
              <a-button
                type="primary"
                :icon="h(HistoryOutlined)"
                class="mr-3"
                @click="onHistory"
                >导出历史</a-button
              >
              <a-button
                type="primary"
                :icon="h(ReconciliationOutlined)"
                class="mr-3"
                @click="onExport"
                >导出信息</a-button
              >
            </a-form-item>
          </a-form>
          <a-table
            :columns="columns"
            :data-source="dataSource"
            bordered
            :pagination="pagination"
            class="mt-5"
            :row-class-name="
              (_record: any, index: number) =>
                index % 2 === 1 ? 'table-striped' : null
            "
            :scroll="{ x: 4500, y: 550 }"
          >
          </a-table>
        </a-card>
      </div>
    </div>
    <a-modal
      title="导出历史"
      :visible="showHistory"
      @cancel="onCancel"
      width="1400px"
    >
      <a-table
        :columns="historyColumns"
        :data-source="historyDataSource"
        bordered
        :pagination="historyPagination"
        class="mt-5"
        :row-class-name="
          (_record: any, index: number) =>
            index % 2 === 1 ? 'table-striped' : null
        "
      >
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.dataIndex === 'states'">
            <a-tag :bordered="false" color="success" v-if="record.states == '0'"
              >完成</a-tag
            >
            <a-tag :bordered="false" color="error" v-else>失败</a-tag>
          </template>
          <template v-if="column.dataIndex === 'active'">
            <a-button type="link" @click="onDown(record)">下载</a-button>
          </template>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, h, onMounted } from 'vue';
import {
  SearchOutlined,
  RedoOutlined,
  HistoryOutlined,
  ReconciliationOutlined,
} from '@ant-design/icons-vue';
import {
  getChargeDailyApi,
  getChargeDailyExportApi,
  getReportExportHistoryApi,
  getOperatorApi,
} from '#/api/core/statistical';
import { getCompanyTree } from '#/api/core/develop';
import { getAllTree } from '#/api/core/customerInformation';
import dayjs from 'dayjs';
import { message } from 'ant-design-vue';
const props = defineProps({
  selectedNodeId: {
    type: Array,
    default: [],
  },
});
const searchFormRef = ref(null);
onMounted(() => {
  getTableData();
});
const comanyList = ref([]);
// const getComany = () => {
//   getAllTree(1, "").then((res: any) => {
//     console.log(res);
//     // 递归处理树形数据，保持层级结构
//     const processTreeData = (tree: any[]): any[] => {
//       return tree.map((item: any) => {
//         console.log(item);
//         const processedItem = {
//           key: item.id,
//           label: item.title,
//           level: item.level,
//           value: item.id,
//           isLeaf: item.level !== 5 ? false : true,
//         };

//         // 如果存在children，递归处理子节点
//         if (item.children && item.children.length > 0) {
//           processedItem.children = processTreeData(item.children);
//         }

//         return processedItem;
//       });
//     };

//     const treeData = processTreeData(res);
//     comanyList.value = treeData;
//     console.log(treeData);
//   });
// };
const getTableData = () => {
  getCompanyTree().then((res: any) => {
    // console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): any[] => {
      console.log(tree);
      return tree.map((item: any) => {
        const processedItem = {
          key: item.id,
          label: item.name,
          value: item.id,
          isLeaf: item.children && item.children.length > 0 ? false : true,
          children: [],
        };

        // 如果存在children，递归处理子节点
        if (item.children && item.children.length > 0) {
          processedItem.children = processTreeData(item.children);
        }

        return processedItem;
      });
    };

    const treeData = processTreeData([res.data]);
    comanyList.value = treeData;
    console.log(comanyList.value);
  });
};

// getComany();
const selectList = ref([]);
const getList = () => {
  getOperatorApi(null)
    .then((res: any) => {
      console.log(res);
      selectList.value = res.map((item: any) => {
        return {
          id: item.id,
          value: item.id,
          title: item.name,
          key: item.id,
          isLeaf: !!item.userId, // 如果有userId说明是叶子节点
        };
      });
    })
    .catch((error) => {
      console.error('获取操作人员列表失败:', error);
      message.error('获取操作人员列表失败');
    });
};
getList();
const onLoadData = (treeNode: any) => {
  return new Promise((resolve) => {
    console.log(treeNode);
    // 如果是叶子节点，直接返回
    if (treeNode.isLeaf) {
      resolve(undefined);
      return;
    }

    // 加载子节点数据
    getOperatorApi(treeNode.id)
      .then((res: any) => {
        const children = res.map((item: any) => {
          console.log(item);
          return {
            id: item.userId ? item.userId : item.id,
            value: item.name ? item.name : item.name,
            title: item.name,
            key: item.userId ? item.userId : item.id,
            isLeaf: !!item.userId, // 如果有userId说明是叶子节点
          };
        });

        // 找到对应的节点并更新其children
        const updateNode = (nodes: any[]) => {
          for (let node of nodes) {
            if (node.key === treeNode.id) {
              node.children = children;
              return true;
            }
            if (node.children && updateNode(node.children)) {
              return true;
            }
          }
          return false;
        };

        updateNode(selectList.value);
        selectList.value = [...selectList.value];
        console.log(selectList.value);
        resolve(undefined);
      })
      .catch((error) => {
        console.error('加载子节点失败:', error);
        message.error('加载子节点失败');
        resolve(undefined);
      });
  });
};
const onLoadDatas = (treeNode: any) => {
  return new Promise((resolve) => {
    console.log(treeNode);
    // 如果是叶子节点，直接返回
    if (treeNode.isLeaf) {
      resolve(undefined);
      return;
    }

    // 加载子节点数据
    getAllTree(1, treeNode.key)
      .then((res: any) => {
        const children = res.map((item: any) => {
          console.log(item);
          return {
            id: item.id ? item.id : item.id,
            value: item.id ? item.id : item.id,
            title: item.title,
            key: item.id ? item.id : item.id,
            isLeaf: item.level !== 5 ? false : true, // 如果有userId说明是叶子节点
          };
        });

        // 找到对应的节点并更新其children
        const updateNode = (nodes: any[]) => {
          console.log(nodes, children);
          for (let node of nodes) {
            if (node.key === treeNode.key) {
              node.children = children;
              return true;
            }
            if (node.children && updateNode(node.children)) {
              return true;
            }
          }
          return false;
        };

        updateNode(comanyList.value);
        comanyList.value = [...comanyList.value];
        console.log(comanyList.value);
        resolve(undefined);
      })
      .catch((error) => {
        console.error('加载子节点失败:', error);
        message.error('加载子节点失败');
        resolve(undefined);
      });
  });
};
const searchForm = reactive({
  time: '',
  comId: undefined,
  feeData: '',
  grState: undefined,
  operator: undefined,
  refundStatus: undefined,
  holder: [],
});
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const historyPagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    historyPagination.current = page;
    historyPagination.pageSize = pageSize;
    onHistory();
  },
});
const showHistory = ref(false);
const historyDataSource = ref([]);
const dataSource = ref([]);
const columns = [
  {
    title: '子公司',
    dataIndex: '',
    key: '',
    align: 'center',
  },
  {
    title: '项目',
    dataIndex: '',
    key: '',
    align: 'center',
  },
  {
    title: '换热站',
    dataIndex: '',
    key: '',
    align: 'center',
  },
  {
    title: '换热站名称(财务)',
    dataIndex: '',
    key: '',
    align: 'center',
  },
  {
    title: '小区名称',
    dataIndex: '',
    key: '',
    align: 'center',
  },
  {
    title: '归属小区',
    dataIndex: '',
    key: '',
    align: 'center',
  },
  {
    title: '收费方式',
    dataIndex: '',
    key: '',
    align: 'center',
  },
  {
    title: '入网数据',
    align: 'center',
    children: [
      {
        title: '居民',
        dataIndex: '',
        key: '',
        align: 'center',
      },
      {
        title: '非居民',
        dataIndex: '',
        key: '',
        align: 'center',
      },
      {
        title: '办公',
        dataIndex: '',
        key: '',
        align: 'center',
      },
      {
        title: '经营',
        dataIndex: '',
        key: '',
        align: 'center',
      },
      {
        title: '小计',
        dataIndex: '',
        key: '',
        align: 'center',
      },
    ],
  },
  {
    title: '入住户数(按入住状态)',
    align: 'center',
    children: [
      {
        title: '居民',
        dataIndex: '',
        key: '',
        align: 'center',
      },
      {
        title: '非居民',
        dataIndex: '',
        key: '',
        align: 'center',
      },
      {
        title: '办公',
        dataIndex: '',
        key: '',
        align: 'center',
      },
      {
        title: '经营',
        dataIndex: '',
        key: '',
        align: 'center',
      },
      {
        title: '小计',
        dataIndex: '',
        key: '',
        align: 'center',
      },
    ],
  },
  {
    title: '建筑面积(整个小区建筑面积,不管应收)',
    align: 'center',
    children: [
      {
        title: '居民',
        dataIndex: '',
        key: '',
        align: 'center',
      },
      {
        title: '非居民',
        dataIndex: '',
        key: '',
        align: 'center',
      },
      {
        title: '办公',
        dataIndex: '',
        key: '',
        align: 'center',
      },
      {
        title: '经营',
        dataIndex: '',
        key: '',
        align: 'center',
      },
      {
        title: '小计',
        dataIndex: '',
        key: '',
        align: 'center',
      },
    ],
  },
  {
    title: '应收全费户数',
    align: 'center',
    children: [
      {
        title: '居民',
        dataIndex: '',
        key: '',
        align: 'center',
      },
      {
        title: '非居民',
        dataIndex: '',
        key: '',
        align: 'center',
      },
      {
        title: '办公',
        dataIndex: '',
        key: '',
        align: 'center',
      },
      {
        title: '经营',
        dataIndex: '',
        key: '',
        align: 'center',
      },
      {
        title: '小计',
        dataIndex: '',
        key: '',
        align: 'center',
      },
    ],
  },
];
const historyColumns = [
  {
    title: '文件名',
    dataIndex: 'fileName',
    key: 'fileName',
    align: 'center',
  },
  {
    title: '操作日期',
    dataIndex: 'operationDate',
    key: 'operationDate',
    align: 'center',
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
    key: 'endTime',
    align: 'center',
  },
  {
    title: '操作人',
    dataIndex: 'operator',
    key: 'operator',
    align: 'center',
  },
  {
    title: '机构',
    dataIndex: 'comName',
    key: 'comName',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'states',
    key: 'states',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'active',
    key: 'active',
    align: 'center',
  },
];
const onSearch = () => {
  if (!props.selectedNodeId || props.selectedNodeId.length === 0) {
    message.error("请选择左侧树结构！");
    return;
  }
  const query = {
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
    time: `${dayjs(searchForm.time[0]).format('YYYY-MM-DD')},${dayjs(
      searchForm.time[1],
    ).format('YYYY-MM-DD')}`,
    comId: searchForm.comId,
    feeData: '',
    grState: '',
    operator: searchForm.operator,
    treeData: props.selectedNodeId,
  };
  // console.log("日报表", query);
  //   getChargeDailyApi(query).then((res: any) => {
  //     console.log("日报表", res);
  //     if (res) {
  //       dataSource.value = res.data;
  //       pagination.total = res.total;
  //     }
  //   });
};
const onExport = () => {
  if (!props.selectedNodeId || props.selectedNodeId.length === 0) {
    message.error("请选择左侧树结构！");
    return;
  }
  const query = {
    time: `${dayjs(searchForm.time[0]).format('YYYY-MM-DD')},${dayjs(
      searchForm.time[1],
    ).format('YYYY-MM-DD')}`,
    comId: '',
    feeData: '',
    grState: '',
    operator: '',
    treeData: props.selectedNodeId,
  };
  getChargeDailyExportApi(query).then((res: any) => {
    console.log('导出信息', res);
    if (res.data.code === 200) {
      message.success(res.data.msg);
    } else {
      message.error('导出失败');
    }
  });
};
const onHistory = () => {
  showHistory.value = true;
  const query = {
    pageNo: historyPagination.current,
    pageSize: historyPagination.pageSize,
    levels: 1,
  };
  getReportExportHistoryApi(query).then((res: any) => {
    console.log('导出历史', res);
    if (res) {
      historyDataSource.value = res.data;
      historyPagination.total = res.total;
    }
  });
};
const onCancel = () => {
  showHistory.value = false;
};
const onDown = (e: any) => {
  // console.log(e);
  const loading = message.loading({
    content: "下载中...",
    duration: 0,
  });

  try {
    // 下载地址拼接
    const url = e.urlAddress;

    // 使用a标签下载，避免X-Frame-Options错误
    const link = document.createElement("a");
    link.href = url;
    link.download = ""; // 触发下载而不是导航
    link.target = "_blank";
    link.style.display = "none";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 关闭loading
    setTimeout(() => {
      loading();
    }, 1000);
  } catch (error) {
    console.error("下载出错:", error);
    message.error("下载出错，请重试");
    loading();
  }
};
const onReset = () => {
  searchFormRef.value.resetFields();
};
</script>
<style scoped>
:deep(.ant-form-item) {
  margin-bottom: 10px !important;
}
</style>
